package com.huaxin.hxmodulesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaxin.hxmodulesystem.dto.ResponseCode;
import com.huaxin.hxmodulesystem.dto.ResponseResult;
import com.huaxin.hxmodulesystem.dto.request.AddRoleReqDTO;
import com.huaxin.hxmodulesystem.dto.request.UpdateRoleReqDTO;
import com.huaxin.hxmodulesystem.mapper.RoleMapper;
import com.huaxin.hxmodulesystem.mapping.RoleMapping;
import com.huaxin.hxmodulesystem.mapping.UserMapping;
import com.huaxin.hxmodulesystem.models.Role;
import com.huaxin.hxmodulesystem.models.User;
import com.huaxin.hxmodulesystem.service.RoleService;
import com.huaxin.hxmodulesystem.service.SysDictionaryService;
import com.huaxin.hxmodulesystem.service.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    private final CacheManager cacheManager;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final ApplicationContext applicationContext;

    private final RoleMapping roleMapping;

    private final UserService userService;

    private final UserMapping userMapping;

    /**
     * 添加角色
     *
     * @param in 用户ID
     * @return 是否成功
     */
    @Override
    public ResponseResult<String> addRole(AddRoleReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        if (StringUtils.isBlank(in.getRoleName())) {
            return ResponseResult.parameterError(null, "角色名称不能为空");
        }
        Role role = roleMapping.toEntity(in);
        if (this.save(role)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "添加角色失败，请稍后再试！", null);
        }
    }

    /**
     * 修改角色
     *
     * @param in 用户ID
     * @return 是否成功
     */
    @Override
    public ResponseResult<String> updateRole(UpdateRoleReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "参数错误");
        }
        if (StringUtils.isBlank(in.getId())) {
            return ResponseResult.parameterError(null, "角色ID不能为空");
        }
        if (StringUtils.isBlank(in.getRoleName())) {
            return ResponseResult.parameterError(null, "角色名称不能为空");
        }
        Role role = this.getById(in.getId());
        roleMapping.updateEntity(in, role);
        if (this.updateById(role)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "修改角色失败，请稍后再试！", null);
        }
    }

    /**
     * 删除角色
     *
     * @return 是否成功
     */
    @Override
    public ResponseResult<String> deleteRole(String id) {
        if (StringUtils.isBlank(id)) {
            return ResponseResult.parameterError(null, "角色ID不能为空");
        }
        Role role = this.baseMapper.selectById(id);
        if (role == null) {
            return ResponseResult.notFound(null, "角色不存在");
        }
        if (applicationContext.getBean(RoleService.class).removeById(id)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "删除角色失败，请稍后再试！", null);
        }
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public Role queryRole(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        User user = userService.getUserInfoById(userId);
        if (user == null) {
            return null;
        }
        return this.getById(user.getRoleId());
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public ResponseResult<Page<Role>> queryAllRole(Integer pageNum, Integer pageSize, String roleName) {
        Page<Role> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(roleName)) {
            wrapper.like("role_name", roleName);
        }
        return ResponseResult.ok(this.baseMapper.selectPage(page, wrapper));
    }

    /**
     * 给用户分配角色
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Override
    @CacheEvict(value = "userInfo", key = "#userId")
    public ResponseResult<String> assignRole(String userId, String roleId) {
        if (StringUtils.isBlank(userId)) {
            return ResponseResult.parameterError(null, "用户ID不能为空");
        }
        if (StringUtils.isBlank(roleId)) {
            return ResponseResult.parameterError(null, "角色ID不能为空");
        }
        User user = userService.getUserInfoById(userId);
        if (user == null) {
            return ResponseResult.parameterError(null, "用户不存在");
        }
        user.setRoleId(roleId);
        if (userService.updateById(user)) {
            return ResponseResult.ok(null);
        } else {
            return ResponseResult.failure(ResponseCode.INTERNAL_ERROR, "分配角色失败，请稍后再试！", null);
        }
    }
}